package top.jacktgq.itheima.netty.protocol_design.groupchat.message;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import top.jacktgq.itheima.netty.protocol_design.groupchat.server.session.Group;
import top.jacktgq.itheima.netty.protocol_design.groupchat.server.session.GroupSessionFactory;

import java.util.List;
import java.util.Set;

@Data
@ToString(callSuper = true)
@Slf4j
public class GroupCreateRequestMessage extends Message {
    private String groupName;
    private Set<String> members;

    public GroupCreateRequestMessage() {
    }

    public GroupCreateRequestMessage(String groupName, Set<String> members) {
        this.groupName = groupName;
        this.members = members;
    }

    @Override
    public int getMessageType() {
        return GroupCreateRequestMessage;
    }

    @Override
    public void handle(ChannelHandlerContext ctx) {
        Group group = GroupSessionFactory.getGroupSession().createGroup(groupName, members);
        log.debug("group：{}", group);
        boolean created = false;
        String reason = "已存在同名群聊，不允许重复创建！";
        if (group == null) {
            created = true;
            reason = "群聊 " + groupName + " 创建成功！";
            // 群发告知加入群聊的成员
            List<Channel> membersChannel = GroupSessionFactory.getGroupSession().getMembersChannel(groupName);
            for (Channel channel : membersChannel) {
                channel.writeAndFlush(new GroupCreateResponseMessage(true, "您已被拉入群聊：" + groupName));
            }
            /*Session session = SessionFactory.getSession();
            for (String member : members) {
                Channel channel = session.getChannel(member);
                // 群友如果在线，就告知
                if (channel != null) {
                    channel.writeAndFlush("您已成功加入群聊：" + groupName);
                }
            }*/
        }
        ctx.writeAndFlush(new GroupCreateResponseMessage(created, reason));
    }
}
